<?php
namespace Core\Mvc;

use Phalcon\Mvc\Controller as PhalconController;
use Phalcon\Di;

class Controller extends PhalconController
{
    public static $variables;

    public function beforeExecuteRoute($dispatcher)
    {
        $this->view->init();
        self::$variables = array(
            'url' => $this->request->getURI(),
            'router_params' => $this->router->getParams(),
        );
        $coreConfig = (object)$this->config->get('m.core.config');
        self::$variables['webConfig'] = $coreConfig;
        foreach (self::$variables['router_params'] as $key => $value) {
            self::$variables[$key] = $value;
        }
    }

    public function afterExecuteRoute($dispatcher)
    {
        //获取控制器监听列表
        $this->view->setVars(self::$variables);
        if (!isset(self::$variables['#templates'])) {
            self::$variables['#templates'] = 'page';
        }
        $this->view->setBaseTemplate(self::$variables['#templates']);
    }

    public function notFount()
    {
        $this->dispatcher->forward(array(
            'controller' => 'Index',
            'action' => 'notFound',
            'namespace' => 'Modules\Core\Controllers',
            'module' => 'core',
        ));
    }

    public function temMoved($url = false)
    {
        $this->view->disable();
        $this->response->setStatusCode(302, 'Temporarily Moved');
        if ($url != false) {
            if (is_array($url)) {
                $url = $this->url->get($url);
            }
        } else {
            if ($this->request->has('rd') && $this->request->get('rd') != self::$variables['url']) {
                $url = $this->request->get('rd');
            } else {
                $url = $this->request->getHTTPReferer();
            }
        }
        $this->response->redirect($url);
        return false;
    }

    public function moved($url = false)
    {
        $this->view->disable();
        if ($url != false) {
            if (is_array($url)) {
                $url = $this->url->get($url);
            }
        } else {
            if ($this->request->has('rd') && $this->request->get('rd') != self::$variables['url']) {
                $url = $this->request->get('rd');
            } else {
                $url = $this->request->getHTTPReferer();
            }
        }
        $this->response->redirect($url);
        return false;
    }
}
